<!-- 采购合同详情 -->
<template>
  <div class="registerDetail">
    <van-nav-bar :title="$route.meta.title" left-text="返回" left-arrow :fixed="true" :placeholder="true" @click-left="$router.go(-1)" />
    <van-swipe class="my-swipe" :autoplay="3000" indicator-color="white">
      <van-swipe-item v-for="(item, index) in dataSource.imageCol" :key="index">
        <img :src="item.imageUrl" />
      </van-swipe-item>
    </van-swipe>
    <div class="car_name">{{ dataSource.carModel }}</div>
    <div class="car_con">
      <div class="car_item">
        <div class="car_icon">
          <i class="iconfont icon-time"></i>
        </div>
        <div class="car_val">{{ dataSource.stockDays }}天</div>
        <div class="car_title">库龄</div>
      </div>
      <div class="car_item">
        <div class="car_icon">
          <i class="iconfont icon-id"></i>
        </div>
        <div class="car_val">{{ dataSource.carNo }}</div>
        <div class="car_title">车牌号码</div>
      </div>
      <div class="car_item">
        <div class="car_icon">
          <i class="iconfont icon-carDate"></i>
        </div>
        <div class="car_val">{{ dataSource.regDate }}</div>
        <div class="car_title">初登日期</div>
      </div>
      <div class="car_item">
        <div class="car_icon">
          <i class="iconfont icon-mlies"></i>
        </div>
        <div class="car_val">{{ dataSource.carMile }}km</div>
        <div class="car_title">行驶里程</div>
      </div>
    </div>
    <div>
      <van-field readonly v-model="dataSource.vinCode" name="车架号" label="车架号" input-align="right" />
      <van-field readonly v-model="dataSource.billStatus" name="库存状态" label="库存状态" input-align="right" />
      <van-field readonly v-model="dataSource.warehouseName" name="采购展厅" label="采购展厅" input-align="right" />
      <van-field readonly v-model="dataSource.warehouseName" name="仓库" label="仓库" input-align="right" />
      <van-field readonly v-model="dataSource.stockDate" name="入库日期" label="入库日期" input-align="right" />
      <van-field readonly v-model="dataSource.inColor" name="内饰颜色" label="内饰颜色" input-align="right" />
      <van-field readonly v-model="dataSource.outColor" name="外饰颜色" label="外饰颜色" input-align="right" />
      <van-field readonly v-model="dataSource.isJM" name="是否寄售车辆" label="是否寄售车辆" input-align="right" />
      <van-field readonly v-model="dataSource.isContract" name="是否生成销售合同" label="是否生成销售合同" label-width="120" placeholder input-align="right" />
    </div>
    <div class="buy_footer flex">
      <div class="buy_footer_item flex" @click="handleBuyContract(dataSource)">
        <div class="buy_footer_lt">
          <div>采购合同</div>
          <div class="txt">
            {{
            dataSource.purchaseCol && dataSource.purchaseCol.length > 0
            ? "点击查看"
            : "未生成"
            }}
          </div>
        </div>
        <div class="buy_footer_rt">
          <van-icon name="arrow" />
        </div>
      </div>
      <div class="buy_footer_item flex" @click="handleSaleContract(dataSource.isContract)">
        <div class="buy_footer_lt">
          <div>销售合同</div>
          <div class="txt">{{ dataSource.isContract == "是" ? "点击查看" : "未生成" }}</div>
        </div>
        <div class="buy_footer_rt">
          <van-icon name="arrow" />
        </div>
      </div>
      <div class="buy_footer_item flex" @click="handleServicingOrder(dataSource)">
        <div class="buy_footer_lt">
          <div>整备工单</div>
          <div class="txt">
            {{
            dataSource.repairWorkCol && dataSource.repairWorkCol.length > 0
            ? "点击查看"
            : "未生成"
            }}
          </div>
        </div>
        <div class="buy_footer_rt">
          <van-icon name="arrow" />
        </div>
      </div>
      <div class="buy_footer_item flex" @click="handleSaleAssess(dataSource)">
        <div class="buy_footer_lt">
          <div>销售线索</div>
          <div class="txt">
            {{
            dataSource.salesLeads && dataSource.salesLeads.length > 0
            ? "点击查看"
            : "未生成"
            }}
          </div>
        </div>
        <div class="buy_footer_rt">
          <van-icon name="arrow" />
        </div>
      </div>
    </div>

    <!-- 转交 -->
    <van-dialog v-model="updateServiceVisible" title="请选择转交跟进人" show-cancel-button @confirm="updateServiceConfirm" :before-close="beforeCloseUpdateTel">
      <van-field v-model="updateServiceData.serverPsnName" name="跟进人" label="跟进人" input-align="right" placeholder="请选择" readonly right-icon="arrow" @click="handleUpdateSelect()" />
    </van-dialog>

    <!-- 操作面板 -->
    <van-share-sheet v-model="showShare" :options="options" @select="onSelect" />
    <div class="morebox">
      <div class="moreBtn" @click="handleShowDo">更多操作</div>
    </div>
  </div>
</template>

<script>
import {
  Empty,
  Field,
  Form,
  ImagePreview,
  ShareSheet,
  Dialog,
  Swipe,
  SwipeItem,
  Notify
} from "vant";
import { getCookies } from "@/utils/util.js";
import icon_edit from "@/assets/images/icon_edit.png";
import icon_foll from "@/assets/images/icon_foll.png";
import icon_zj from "@/assets/images/icon_zj.png";
import ico_apply from "@/assets/images/ico_apply.png";
import icon_buy from "@/assets/images/icon_buy.png";
import white_png from "@/assets/images/white.png";
import sellManageApi from "@/api/sellManageApi";
import qs from "qs";
import axios from "axios";
const base_url = process.env.BASE_API;
export default {
  name: "buyContractDetail",
  components: {
    Empty,
    Field,
    Form,
    ImagePreview,
    ShareSheet,
    Dialog,
    Swipe,
    SwipeItem,
    Notify
  },
  data() {
    return {
      showTimerPicker: false,
      dataSource: {
        inColor: "", //内饰颜色
        outColor: "", //外饰颜色
        isJM: "", //是否寄售
        isContract: "", //是否生成销售合同
        billId: "", //单据Id
        carNo: "", //车牌号
        warehouseName: "", //仓库
        vinCode: "", //车架号
        carModel: "", //二手车模型
        billStatus: "", //库存状态
        regDate: "", //初次登记日期
        stockDate: "", //入库日期
        stockDays: "", //库龄
        showOrgName: "", //采购展厅
        carMile: "" //行驶里程数
      },
      uploader: [],
      columns: [],
      showSelectPicker: false,
      disabled: false,
      detailId: "",
      tabActive: 0,
      userId: getCookies("userId"), //用户ID，必填，String
      showShare: false,
      options: [
        [
          { name: "生成整备工单", icon: icon_foll, value: 2 },
          { name: "申请竞拍", icon: icon_edit, value: 1 },
          { name: "退库", icon: icon_buy, value: 6 }
          // { name: '上架懂车帝店铺', icon: icon_buy, value: 5 },
        ],
        [
          { name: "生成销售合同", icon: icon_zj, value: 3 },
          { name: "上架易手车商城", icon: ico_apply, value: 4 },
          { name: "", icon: white_png, value: 99 }
        ]
      ],
      updateServiceVisible: false,
      updateServiceData: {
        fixCenterId: "",
        fixCenterName: "",
        currentServerPsnName: "",
        serverPsnName: "",
        serverPsnId: "",
        id: "",
        userId: ""
      },
      userInfo: {}
    };
  },

  mounted() {
    if (localStorage.getItem("billId")) {
      this.detailId = localStorage.getItem("billId");
      this.getDetail(this.detailId);
    }
    if (localStorage.getItem("userInfo")) {
      this.userInfo = JSON.parse(localStorage.getItem("userInfo"));
      console.log(this.userInfo);
    }
    // if (this.$route.query) {
    //   this.detailId = this.$route.query.billId
    //   this.getDetail(this.detailId)
    // }
  },
  methods: {
    getDetail(billId) {
      sellManageApi
        .secondHandCarFacade({
          billId,
          method: "getCarStockById"
        })
        .then(res => {
          if (res.code == 1) {
            this.dataSource = res.data;
            this.dataSource.isJM = this.dataSource.isJM == 1 ? "是" : "否";
            this.dataSource.isContract =
              this.dataSource.isContract == 1 ? "是" : "否";
            // localStorage.removeItem("billId");
          }
        });
    },

    // 选择下拉
    handleSelect(field) {
      if (this.disabled) {
        return;
      }
      this.showSelectPicker = true;
      if (field == "repair") {
        this.columns = [
          { name: "是", value: 1 },
          { name: "否", value: 2 }
        ];
      } else if (field == "outUser") {
        this.columns = [
          { name: "服务人员1", value: 1 },
          { name: "服务人员2", value: 2 }
        ];
      }
      this.field = field;
    },
    // 选择下拉确认
    handleSelectConfirm(value, index) {
      this.dataSource[this.field] = value.name;
      this.showSelectPicker = false;
    },

    onConfirm(val, field) {
      let year = val.getFullYear();
      let month = val.getMonth() + 1;
      let day = val.getDate();
      let hour = val.getHours();
      let minute = val.getMinutes();
      // let second = val.getSeconds()
      if (month >= 1 && month <= 9) {
        month = `0${month}`;
      }
      if (day >= 1 && day <= 9) {
        day = `0${day}`;
      }
      if (hour >= 0 && hour <= 9) {
        hour = `0${hour}`;
      }
      if (minute >= 0 && minute <= 9) {
        minute = `0${minute}`;
      }
      // if (second >= 0 && second <= 9) { second = `0${second}` }
      this.dataSource[field] = `${year}-${month}-${day} ${hour}:${minute}:00`;
      this.showTimerPicker = false;
    },

    formatter(type, value) {
      if (type === "year") {
        return `${value}年`;
      } else if (type === "month") {
        return `${value}月`;
      } else if (type === "day") {
        return `${value}日`;
      } else if (type === "hour") {
        return `${value}时`;
      } else if (type === "minute") {
        return `${value}分`;
      } else if (type === "second") {
        return `${value}秒`;
      }
      return value;
    },
    //维修预约
    applyRepair() {
      this.$router.push("/applyRepair");
    },
    // 获取list名称
    getFieldName(list, key, val) {
      if (list && list.length > 0) {
        let obj = list.filter(item => {
          return item[key] == val;
        });
        if (obj.length > 0) {
          return obj[0].name;
        }
      }
      return null;
    },

    handleShowDo() {
      this.showShare = true;
    },
    onSelect(option) {
      let vm = this;
      if (option.value == 1) {
        Dialog.confirm({
          title: "提示",
          message: `确定申请竞拍？`
        })
          .then(() => {
            vm.applyEst(option.value);
          })
          .catch(() => {
            console.log("取消");
            // on cancel
          });
      }
      if (option.value == 2) {
        if (
          this.dataSource.repairWorkCol &&
          this.dataSource.repairWorkCol.length > 0
        ) {
          Notify({ type: "danger", message: "已有整备工单，无法再次生成" });
          return;
        }
        Dialog.confirm({
          title: "提示",
          message: `确定生成整备工单？`
        })
          .then(() => {
            sellManageApi
              .secondHandCarFacade({
                method: "carStockGenServiceWorkByBOTP", //固定值
                carStockId: this.detailId //单据Id，必填，String
              })
              .then(res => {
                if (res.code == 1) {
                  this.getDetail(this.detailId);
                  Notify({ type: "success", message: "生成生成整备工单成功" });
                }
              });
          })
          .catch(() => {
            console.log("取消");
            // on cancel
          });
      }
      if (option.value == 3) {
        console.log(this.dataSource.isContract);
        if (this.dataSource.isContract && this.dataSource.isContract != "否") {
          Notify({ type: "danger", message: "已有销售合同，无法再次生成" });
          return;
        }
        Dialog.confirm({
          title: "提示",
          message: `确定生成销售合同？`
        })
          .then(() => {
            sellManageApi
              .secondHandCarFacade({
                method: "carStockGenContractByBOTP", //固定值
                carStockId: this.detailId //单据Id，必填，String
              })
              .then(res => {
                if (res.code == 1) {
                  this.getDetail(this.detailId);
                  Notify({ type: "success", message: "生成销售合同成功" });
                }
              });
          })
          .catch(() => {
            console.log("取消");
            // on cancel
          });
      }
      if (option.value == 4) {
        this.$router.push({
          path: "/YscShop",
          query: {
            billId: this.dataSource.billId,
            vinCode: this.dataSource.vinCode,
            carId: this.dataSource.carId
          }
        });
      }
      if (option.value == 5) {
        Dialog.confirm({
          title: "提示",
          message: `确定上架懂车帝店铺？`
        })
          .then(() => {
            // sellManageApi
            //   .secondHandCarFacade({
            //     method: 'purContractToPurInWareByBOTP', //固定值
            //     purContractId: this.detailId, //单据Id，必填，String
            //   })
            //   .then((res) => {
            //     if (res.code == 1) {
            //       Notify({ type: 'success', message: '生成采购入库成功' })
            //     }
            //   })
          })
          .catch(() => {
            console.log("取消");
            // on cancel
          });
      }
      if (option.value == 6) {
        if (this.dataSource.isContract == "是") {
          Notify({ type: "danger", message: "已有销售合同，该车不能退库" });
          return;
        }
        Dialog.confirm({
          title: "提示",
          message: `确定退库？`
        })
          .then(() => {
            sellManageApi
              .secondHandCarFacade({
                method: "purInToRedPurInByBOTP", //固定值
                stockInId: this.dataSource.stockInId //单据Id，必填，String
              })
              .then(res => {
                if (res.code == 1) {
                  Notify({ type: "success", message: "退库成功" });
                  this.getDetail(vm.detailId);
                }
              });
          })
          .catch(() => {
            console.log("取消");
            // on cancel
          });
      }

      this.showShare = false;
    },

    applyEst(type) {
      let vm = this;
      axios({
        url: `${base_url}/proxy/qywx/jsdkConfig`,
        method: "post",
        data: qs.stringify(
          // { url: 'http://wycl.autocnd.com:41080/ysc/assessManageDetail' },
          { url: location.href.split("?")[0], type: "app" },
          { encode: false }
        ),
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
          satoken: getCookies("token")
        }
      }).then(res => {
        console.log("jsdkConfig:", res);
        let jsdk = res.data.data;
        localStorage.setItem("jsdk", JSON.stringify(res.data.data));
        wx.agentConfig({
          corpid: jsdk.corpid, // 必填，企业微信的corpid，必须与当前登录的企业一致
          agentid: jsdk.agentid, // 必填，企业微信的应用id （e.g. 1000247）
          timestamp: jsdk.timestamp, // 必填，生成签名的时间戳
          nonceStr: jsdk.nonceStr, // 必填，生成签名的随机串
          signature: jsdk.signature, // 必填，签名，见附录-JS-SDK使用权限签名算法
          jsApiList: ["launchMiniprogram"], //必填，传入需要使用的接口名称
          success: function(res) {
            console.log("agentConfig权限成功返回信息:", res);
            // wx9e482fe1abf18c87
            // appid: 'wx02e51afc29cecca4', // 需跳转的小程序appid
            if (type == 1) {
              console.log(
                "申请竞拍跳转地址：",
                `/trade/auctionVehicle/edit/auctionVehicleEdit?ysc=1&username=${
                  vm.userInfo ? vm.userInfo.kdaccount : "zhangdx"
                }&stock=${encodeURIComponent(vm.detailId)}`
              );
              // 申请竞拍
              wx.invoke(
                "launchMiniprogram",
                {
                  appid: "wx02e51afc29cecca4", // 需跳转的小程序appid
                  // appid: 'wx9e482fe1abf18c87', // 测试跳转的appid
                  path: `/trade/auctionVehicle/edit/auctionVehicleEdit?ysc=1&username=${
                    vm.userInfo ? vm.userInfo.kdaccount : "zhangdx"
                  }&stock=${encodeURIComponent(this.detailId)}` // 所需跳转的小程序内页面路径及参数。非必填
                },
                function(res) {
                  if (res.err_msg == "launchMiniprogram:ok") {
                    // 正常
                  } else {
                    // 错误处理
                  }
                }
              );
            }
          },
          fail: function(res) {
            console.log("agentConfig权限失败返回信息:", res);
            if (res.errMsg.indexOf("function not exist") > -1) {
              alert("版本过低请升级");
            }
          }
        });
      });
    },

    // 确认转交
    updateServiceConfirm() {
      console.log(this.updateServiceData);
      if (!this.updateServiceData.serverPsnId) {
        Notify({ type: "danger", message: "请选择跟进人" });
        return;
      }
      carApi
        .updateServerPsnAndFixCenter({
          id: this.updateServiceData.id, //单车表id，String，必填
          fixCenterId: this.updateServiceData.fixCenterId, //送修人电话，String，必填
          serverPsnId: this.updateServiceData.serverPsnId,
          userId: this.requestParams.userId //用户ID，必填，String
        })
        .then(res => {
          if (res.code == 1) {
            Notify({ type: "success", message: "更新成功" });
            this.initData();
          } else {
            Notify({ type: "danger", message: res.errorMessage });
          }
        });

      this.updateServiceVisible = false;
    },
    beforeCloseUpdateTel(action, done) {
      if (action === "confirm") {
        return done(false);
      } else {
        return done();
      }
    },
    handleUpdateSelect() {},
    handleAssessDetail() {
      this.$router.push({
        path: "/assessManageDetail",
        query: { leadsPurId: this.dataSource.leadsPurId }
      });
    },
    handleFile() {
      this.$router.push({
        path: "/fileMange",
        query: { billId: this.detailId }
      });
    },
    handlePayOrder() {
      this.$router.push({
        path: "/PaymentOrder",
        query: { billId: this.detailId }
      });
    },
    handleCarStorge() {
      this.$router.push({
        path: "/CarStorge",
        query: { billId: this.detailId }
      });
    },
    // 采购合同
    handleBuyContract(status) {
      if (status.purchaseCol.length < 1) {
        return;
      }
      this.$router.push({
        path: "/buyContractDetail",
        query: {
          billId: status.purchaseCol[0].billId,
          list: status.purchaseCol
        }
      });
    },
    // 销售合同
    handleSaleContract(status) {
      if (status == "否") {
        return;
      }
      sellManageApi
        .secondHandCarFacade({
          method: "getDestInfoBySourceIdAndDestBosType", //固定值
          billId: this.detailId,
          desBosType: "3B39DC07" //单据类型BOSType，必填，String
        })
        .then(res => {
          if (res.code == 1) {
            if (res.data.length >= 1) {
              this.$router.push({
                path: "/salesManageDetail",
                query: { billId: res.data[0].billId }
              });
            } else {
              this.$toast.fail("暂无该单据");
            }
          } else {
            this.$toast.fail("暂无该单据");
          }
        });
    },
    // 整备工单
    handleServicingOrder(status) {
      if (!status.repairWorkCol || status.repairWorkCol.length < 1) {
        return;
      }
      this.$router.push({
        path: "/RepairOrder",
        query: {
          billId: status.repairWorkCol[0].billId,
          list: status.repairWorkCol
        }
      });
    },
    // 销售线索
    handleSaleAssess(status) {
      if (!status.salesLeads || status.salesLeads.length < 1) {
        return;
      }
      this.$router.push({
        path: "/salesLeadsDetails",
        query: { billId: status.salesLeads[0].billId, list: status.salesLeads }
      });
    }
  }
};
</script>

<style lang="less" scoped>
.van-field {
  // font-size:16px;
}
body {
  background: #f3f3f3;
}
.flex {
  display: flex;
  align-items: center;
}
.van-swipe-item {
  width: 100%;

  img {
    width: 100%;
    display: block;
  }
}
.registerDetail {
  padding-bottom: 75px;
  .top_detail {
    display: flex;
    align-items: center;
    // width: 100%;
    background: #fff;
    padding: 10px;
    margin: 10px;
    .top_detail_lt {
      display: inline-block;
      text-align: center;
      width: 50%;
      border-right: 1px solid #f0f0f0;
    }
    .top_detail_rt {
      width: 50%;
      display: inline-block;
      text-align: center;
    }
    .top_name {
      font-weight: bold;
      font-size: 16px;
      margin-bottom: 5px;
    }
    .top_status {
      color: red;
      font-size: 16px;
      margin-bottom: 5px;
    }
    .top_txt {
      font-size: 16px;
      color: #333;
      margin-bottom: 5px;
      .icon-tel {
        background: #35bc04;
        color: #fff;
        border-radius: 50%;
        padding: 5px;
      }
    }
  }
}
.buy_content {
  .buy_name {
    background: #fff;
    font-size: 15px;
    font-weight: bold;
    margin-bottom: 15px;
    padding-top: 5px;
  }
  .carInfo {
    padding: 10px;
    background: #fff;
    margin-bottom: 10px;
    .source {
      padding-left: 0 !important;
      margin-bottom: 10px;
      justify-content: space-between;

      .source_txt {
        font-size: 16px;
      }
    }

    .carInfo_No {
      margin-bottom: 15px;
      .carInfo_No_item {
        border-right: 1px solid #ccc;
        padding-right: 5px;
        margin-right: 5px;
        font-size: 16px;
        color: #333;
        &:last-child {
          border: none;
        }
      }
    }
    .carInfo_item {
      font-size: 16px;
      margin-bottom: 5px;
      color: #333;
      .carInfo_item_price {
        width: 50%;
      }
    }
    .carInfo_title {
      font-size: 16px;
      color: #333;
      margin-bottom: 10px;
      font-weight: bold;
    }
  }
}
.buy_footer {
  background: #fff;
  flex-wrap: wrap;
  box-sizing: border-box;
  width: 100%;
  .buy_footer_item {
    box-sizing: border-box;
    width: 50%;
    padding: 15px;
    justify-content: space-between;
    border-bottom: 1px solid #f5f5f5;
    border-right: 1px solid #f5f5f5;
    .buy_footer_lt {
      font-size: 16px;
      color: #333;
      padding-left: 15px;
      .txt {
        color: #bbbbbb;
        margin-top: 10px;
        font-size: 14px;
      }
    }
    .buy_footer_rt {
    }
  }
}

.morebox {
  position: fixed;
  bottom: 0;
  left: 0;
  z-index: 99;
  width: 100%;
  background: #fff;
  .moreBtn {
    background: #409eff;
    color: #fff;
    width: 75%;
    margin: auto;
    text-align: center;
    padding: 12px;
    border-radius: 5px;
    margin-top: 15px;
    font-size: 15px;
    margin-bottom: 25px;
  }
}
/deep/ .van-share-sheet__icon {
  width: 40px;
  height: 40px;
}
.car_name {
  background: #fff;
  padding: 15px 10px 0 10px;
  font-size: 16px;
  color: #333;
  line-height: 18px;
  font-weight: bold;
}
.car_con {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 10px;
  background: #fff;
  border-bottom: 4px solid #efefef;
  .car_item {
    width: 25%;
    text-align: center;
    .car_icon {
      color: #999;
      margin-bottom: 10px;
    }
    .icon-time {
      font-size: 27px;
    }
    .icon-id {
      font-size: 27px;
    }
    .icon-carDate {
      font-size: 27px;
    }
    .icon-mlies {
      font-size: 27px;
    }
    .car_val {
      font-size: 14px;
      color: #333;
      margin-bottom: 10px;
    }
    .car_title {
      font-size: 14px;
      color: #999;
    }
  }
}
</style>
